import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    auth: {
      isLoggedIn: false,
      user: null
    }
  },
  mutations: {
    SET_AUTH(state, user) {
      state.auth.isLoggedIn = true
      state.auth.user = user
    },
    CLEAR_AUTH(state) {
      state.auth.isLoggedIn = false
      state.auth.user = null
    }
  },
  actions: {
    async login({ commit }, credentials) {
      const response = await axios.post('/api/auth/login', credentials)
      const { user } = response.data
      commit('SET_AUTH', user)
    },
    async logout({ commit }) {
      await axios.post('/api/auth/logout')
      commit('CLEAR_AUTH')
    },
    async checkAuth({ commit }) {
      try {
        const response = await axios.get('/api/auth/profile')
        commit('SET_AUTH', response.data)
      } catch (error) {
        commit('CLEAR_AUTH')
      }
    }
  },
  modules: {
  }
}) 